package com.datastructure.stack;

public class LinkedStack implements MyStack{
    StackNode top;//top是正真top节点的前一个节点，类似于头节点
    LinkedStack() {
        top = new StackNode(-1);
    }
    //入栈
    //将新节点插入到头节点后面
    @Override
    public void push(int value) {
        if (isFull()) {
            System.out.println("栈满");
            return;
        }
        StackNode newNode = new StackNode(value);
        newNode.next = top.next;
        top.next = newNode;
        System.out.println("新增元素：" + value);
    }

    //出栈
    //将 top.next 指向原 top.next 的后一个节点
    @Override
    public int pop() {
        if (isEmpty()){
            System.out.println("栈空");
            throw new RuntimeException("栈空，无法弹出");
        }
        int value = top.next.value;
        top.next = top.next.next;
        return value;
    }

    @Override
    public void show() {
        if(isEmpty()) {
            System.out.println("栈空");
            return;
        }
        System.out.println("当前栈为");
        StackNode temp = top.next;
        while (temp != null) {
            System.out.println(temp.value);
            temp = temp.next;
        }
    }

    //栈空
    @Override
    public boolean isEmpty() {
        return top.next == null;
    }

    //这里不设置栈大小，假设栈始终不满
    @Override
    public boolean isFull() {
        return false;
    }
}

class StackNode {
    int value; //值
    StackNode next; //指向下一个节点
    StackNode(int value) {
        this.value = value;
        this.next = null;
    }
}
